<template>
  <!-- 主内容区域 -->
  <div class="content-area">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon income">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                ¥{{ formatAmount(stats.totalIncome) }}
              </div>
              <div class="stat-label">今日收入</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon pending">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.pendingCount }}</div>
              <div class="stat-label">待收费</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon completed">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.completedCount }}</div>
              <div class="stat-label">已收费</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon refund">
              <el-icon><Refresh /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.refundCount }}</div>
              <div class="stat-label">退款单</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">患者姓名</div>
          <el-input
            v-model="filters.patientName"
            placeholder="请输入患者姓名"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">挂号单号</div>
          <el-input
            v-model="filters.appointmentId"
            placeholder="请输入挂号单号"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">收费状态</div>
          <el-select
            v-model="filters.paymentStatus"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="待收费" value="pending" />
            <el-option label="已收费" value="completed" />
            <el-option label="已退款" value="refunded" />
            <el-option label="部分退款" value="partial_refund" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">收费类型</div>
          <el-select
            v-model="filters.paymentType"
            placeholder="请选择类型"
            clearable
          >
            <el-option label="挂号收费" value="registration" />
            <el-option label="检查收费" value="examination" />
            <el-option label="药品收费" value="medicine" />
            <el-option label="治疗收费" value="treatment" />
            <el-option label="住院预交金" value="inpatient_deposit" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">日期范围</div>
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchPayments">查询</el-button>
        <!-- 已移除新建挂号按钮 -->
        <el-button type="warning" @click="exportStatement">
          <el-icon><Document /></el-icon>
          导出对账单
        </el-button>
      </div>
    </div>

    <!-- 收费表格 -->
    <div class="payment-table">
      <div class="table-header">
        <div class="table-title">收费记录</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table :data="payments" style="width: 100%" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="paymentNo" label="收费单号" width="140" />
        <el-table-column label="患者信息" min-width="180">
          <template #default="{ row }">
            <div class="patient-info">
              <div class="patient-avatar">
                <el-avatar :size="40" :src="row.patientAvatar" />
              </div>
              <div>
                <div>{{ row.patientName }}</div>
                <div style="font-size: 12px; color: #909399">
                  {{ row.appointmentId }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="paymentType" label="收费类型" width="100">
          <template #default="{ row }">
            {{ formatPaymentType(row.paymentType) }}
          </template>
        </el-table-column>
        <el-table-column label="来源单据" width="120">
          <template #default="{ row }">
            <span v-if="row.sourceType === 'prescription'"
              >处方{{ row.sourceId }}</span
            >
            <span v-else-if="row.sourceType === 'examination'"
              >检查单{{ row.sourceId }}</span
            >
            <span v-else-if="row.sourceType === 'treatment'"
              >治疗单{{ row.sourceId }}</span
            >
            <span v-else-if="row.sourceType === 'registration'"
              >挂号单{{ row.sourceId }}</span
            >
            <span v-else>{{ row.sourceType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应收金额" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.payableAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="优惠金额" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.discountAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="实收金额" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ formatAmount(row.actualAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="医保支付" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.insurancePayment) }}
          </template>
        </el-table-column>
        <el-table-column label="个人支付" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.personalPayment) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.paymentStatus)" size="small">
              {{ formatPaymentStatus(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button size="small" @click="viewPaymentDetails(row)"
                >详情</el-button
              >
              <el-button
                size="small"
                type="primary"
                :disabled="row.paymentStatus !== 'pending'"
                @click="processPayment(row)"
              >
                {{ row.paymentStatus === "pending" ? "收费" : "已收费" }}
              </el-button>
              <el-button
                size="small"
                type="danger"
                :disabled="row.paymentStatus !== 'completed'"
                @click="showRefundDialog(row)"
              >
                退款
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 收费处理对话框 -->
    <el-dialog
      v-model="paymentProcessDialog.visible"
      :title="`收费处理 - ${currentPayment?.patientName}`"
      width="700px"
    >
      <div v-if="currentPayment" class="payment-process">
        <!-- 费用明细 -->
        <div class="fee-details">
          <h4>费用明细</h4>
          <el-table :data="currentPayment.items" border style="width: 100%">
            <el-table-column prop="itemName" label="项目名称" />
            <el-table-column prop="specification" label="规格" width="100" />
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="{ row }"
                >¥{{ formatAmount(row.unitPrice) }}</template
              >
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="amount" label="金额" width="100">
              <template #default="{ row }"
                >¥{{ formatAmount(row.amount) }}</template
              >
            </el-table-column>
          </el-table>
        </div>

        <!-- 费用汇总 -->
        <div class="fee-summary">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="应收金额">
              ¥{{ formatAmount(currentPayment.payableAmount) }}
            </el-descriptions-item>
            <el-descriptions-item label="优惠金额">
              <el-input-number
                v-model="paymentProcessForm.discountAmount"
                :min="0"
                :max="currentPayment.payableAmount"
                :precision="2"
                controls-position="right"
                style="width: 200px"
              />
            </el-descriptions-item>
            <el-descriptions-item label="医保支付">
              <el-input-number
                v-model="paymentProcessForm.insurancePayment"
                :min="0"
                :max="
                  currentPayment.payableAmount -
                  paymentProcessForm.discountAmount
                "
                :precision="2"
                controls-position="right"
                style="width: 200px"
              />
            </el-descriptions-item>
            <el-descriptions-item label="个人支付">
              ¥{{ formatAmount(personalPaymentAmount) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 支付信息 -->
        <div class="payment-info">
          <el-form :model="paymentProcessForm" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="支付方式" prop="paymentMethod">
                  <el-select
                    v-model="paymentProcessForm.paymentMethod"
                    placeholder="请选择支付方式"
                  >
                    <el-option label="现金" value="cash" />
                    <el-option label="银行卡" value="card" />
                    <el-option label="微信支付" value="wechat" />
                    <el-option label="支付宝" value="alipay" />
                    <el-option label="医保结算" value="insurance" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收费窗口" prop="windowNumber">
                  <el-input
                    v-model="paymentProcessForm.windowNumber"
                    placeholder="请输入窗口号"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="notes">
              <el-input
                v-model="paymentProcessForm.notes"
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <el-button @click="paymentProcessDialog.visible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="confirmPayment">确认收费</el-button>
      </template>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog v-model="refundDialog.visible" title="退款处理" width="500px">
      <el-form :model="refundForm" label-width="100px">
        <el-form-item label="退款单号">
          {{ refundForm.refundNo }}
        </el-form-item>
        <el-form-item label="原收费单号">
          {{ refundForm.paymentNo }}
        </el-form-item>
        <el-form-item label="患者姓名">
          {{ refundForm.patientName }}
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input-number
            v-model="refundForm.refundAmount"
            :min="0"
            :max="refundForm.originalAmount"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="退款方式" prop="refundMethod">
          <el-select
            v-model="refundForm.refundMethod"
            placeholder="请选择退款方式"
          >
            <el-option label="原路退回" value="original" />
            <el-option label="现金退款" value="cash" />
            <el-option label="银行转账" value="transfer" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input
            v-model="refundForm.refundReason"
            type="textarea"
            :rows="3"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确认退款</el-button>
      </template>
    </el-dialog>

    <!-- 收费详情抽屉 -->
    <el-drawer
      v-model="detailDrawer.visible"
      title="收费详情"
      :direction="'rtl'"
      size="40%"
    >
      <div class="payment-detail" v-if="currentPayment">
        <div class="detail-header">
          <h3>收费单号：{{ currentPayment.paymentNo }}</h3>
          <el-tag
            :type="getStatusType(currentPayment.paymentStatus)"
            size="large"
          >
            {{ formatPaymentStatus(currentPayment.paymentStatus) }}
          </el-tag>
        </div>

        <el-divider />

        <div class="detail-section">
          <h4>患者信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="患者姓名">{{
              currentPayment.patientName
            }}</el-descriptions-item>
            <el-descriptions-item label="挂号单号">{{
              currentPayment.appointmentId
            }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{
              currentPayment.idNumber
            }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{
              currentPayment.phoneNumber
            }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h4>收费信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="收费类型">{{
              formatPaymentType(currentPayment.paymentType)
            }}</el-descriptions-item>
            <el-descriptions-item label="来源单据">
              <span v-if="currentPayment.sourceType === 'prescription'"
                >处方{{ currentPayment.sourceId }}</span
              >
              <span v-else-if="currentPayment.sourceType === 'examination'"
                >检查单{{ currentPayment.sourceId }}</span
              >
              <span v-else-if="currentPayment.sourceType === 'treatment'"
                >治疗单{{ currentPayment.sourceId }}</span
              >
              <span v-else-if="currentPayment.sourceType === 'registration'"
                >挂号单{{ currentPayment.sourceId }}</span
              >
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">{{
              formatPaymentMethod(currentPayment.paymentMethod)
            }}</el-descriptions-item>
            <el-descriptions-item label="应收金额"
              >¥{{
                formatAmount(currentPayment.payableAmount)
              }}</el-descriptions-item
            >
            <el-descriptions-item label="优惠金额"
              >¥{{
                formatAmount(currentPayment.discountAmount)
              }}</el-descriptions-item
            >
            <el-descriptions-item label="医保支付"
              >¥{{
                formatAmount(currentPayment.insurancePayment)
              }}</el-descriptions-item
            >
            <el-descriptions-item label="个人支付"
              >¥{{
                formatAmount(currentPayment.personalPayment)
              }}</el-descriptions-item
            >
            <el-descriptions-item label="实收金额"
              >¥{{
                formatAmount(currentPayment.actualAmount)
              }}</el-descriptions-item
            >
            <el-descriptions-item label="收费时间">{{
              formatDateTime(currentPayment.paymentTime)
            }}</el-descriptions-item>
            <el-descriptions-item label="操作员">{{
              currentPayment.operatorName
            }}</el-descriptions-item>
            <el-descriptions-item label="收费窗口">{{
              currentPayment.windowNumber
            }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h4>费用明细</h4>
          <el-table :data="currentPayment.items" border style="width: 100%">
            <el-table-column prop="item_name" label="项目名称" />
            <el-table-column prop="category_name" label="类别" width="100" />
            <el-table-column prop="unit_price" label="单价" width="100">
              <template #default="{ row }"
                >¥{{ formatAmount(row.unit_price) }}</template
              >
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="amount" label="金额" width="100">
              <template #default="{ row }"
                >¥{{ formatAmount(row.amount) }}</template
              >
            </el-table-column>
          </el-table>
        </div>

        <div class="detail-section" v-if="currentPayment.notes">
          <h4>备注</h4>
          <p>{{ currentPayment.notes }}</p>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
// 引入API接口
import { getPaymentPagerDataBySearch, getPaymentDetailById } from "@/api/api";

const router = useRouter();
const store = useStore();

// 当前登录用户名
const username = ref(store.state.user?.username || "收费员01");

// 筛选条件
const filters = reactive({
  patientName: "",
  appointmentId: "",
  paymentStatus: "",
  paymentType: "",
  dateRange: [],
});

// 初始化统计信息
const stats = reactive({
  totalIncome: 0,
  pendingCount: 0,
  completedCount: 0,
  refundCount: 0,
});

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 收费数据
const payments = ref([]);

// 收费处理对话框相关
const paymentProcessDialog = reactive({
  visible: false,
});

const paymentProcessForm = reactive({
  discountAmount: 0,
  insurancePayment: 0,
  paymentMethod: "cash",
  windowNumber: "01",
  notes: "",
});

// 退款对话框相关
const refundDialog = reactive({
  visible: false,
});

const refundForm = reactive({
  paymentNo: "",
  refundNo: "",
  patientName: "",
  originalAmount: 0,
  refundAmount: 0,
  refundMethod: "original",
  refundReason: "",
});

// 详情抽屉相关
const detailDrawer = reactive({
  visible: false,
});

const currentPayment = ref(null);

// 计算属性：计算个人支付金额
const personalPaymentAmount = computed(() => {
  if (!currentPayment.value) return 0;
  const payable = currentPayment.value.payableAmount;
  const discount = paymentProcessForm.discountAmount;
  const insurance = paymentProcessForm.insurancePayment;
  return payable - discount - insurance;
});

// 方法
const resetFilters = () => {
  filters.patientName = "";
  filters.appointmentId = "";
  filters.paymentStatus = "";
  filters.paymentType = "";
  filters.dateRange = [];
  loadPayments();
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "";

  // 如果是ISO格式的时间字符串
  if (typeof dateTime === "string" && dateTime.includes("T")) {
    return dateTime.replace("T", " ").split(".")[0];
  }

  // 其他格式直接返回
  return dateTime;
};

const searchPayments = () => {
  pagination.currentPage = 1;
  loadPayments();
};

// 加载收费分页数据
const loadPayments = async () => {
  // 构建查询参数
  const params = {
    patientName: filters.patientName,
    appointmentId: filters.appointmentId,
    paymentStatus: filters.paymentStatus,
    paymentType: filters.paymentType,
    startDate: filters.dateRange.length === 2 ? filters.dateRange[0] : null,
    endDate: filters.dateRange.length === 2 ? filters.dateRange[1] : null,
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
  };

  // 异步获取数据
  const response = await getPaymentPagerDataBySearch(params);

  //console.log("收费分页数据：", response);

  if (response && response.code == 200) {
    // 兼容后端 data 结构
    payments.value = Array.isArray(response.data?.data)
      ? response.data.data
      : [];
    pagination.total = response.data?.total ?? payments.value.length;

    // 更新统计信息
    updateStatistics();
  } else {
    ElMessage.error(response?.msg || "加载收费数据失败");
  }
};

// 更新统计信息
const updateStatistics = () => {
  const today = new Date().toISOString().split("T")[0];

  const todayPayments = payments.value.filter((payment) => {
    return payment.createTime && payment.createTime.includes(today);
  });

  stats.totalIncome = todayPayments
    .filter((p) => p.paymentStatus === "completed")
    .reduce((sum, p) => sum + (p.actualAmount || 0), 0);

  stats.pendingCount = payments.value.filter(
    (p) => p.paymentStatus === "pending"
  ).length;
  stats.completedCount = payments.value.filter(
    (p) => p.paymentStatus === "completed"
  ).length;
  stats.refundCount = payments.value.filter(
    (p) =>
      p.paymentStatus === "refunded" || p.paymentStatus === "partial_refund"
  ).length;
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadPayments();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadPayments();
};

// 查看收费详情
const viewPaymentDetails = (payment) => {
  currentPayment.value = payment;

  // 如果当前payment没有items数据，则从后端获取详情
  if (!payment.items || payment.items.length === 0) {
    console.log("后端调用API");
    loadPaymentDetail(payment.paymentId);
  } else {
    console.log("加载已有数据");
    detailDrawer.visible = true;
  }
  detailDrawer.visible = true;
};

// 加载收费详情
const loadPaymentDetail = async (paymentId) => {
  try {
    // 这里需要调用新的API接口获取收费详情
    const response = await getPaymentDetailById({ paymentId: paymentId });
    console.log(response);
    if (response && response.code === 200) {
      currentPayment.value = response.data;
      detailDrawer.visible = true;
    }

    // 临时方案：使用现有数据
    detailDrawer.visible = true;
  } catch (error) {
    console.error("加载收费详情失败:", error);
    ElMessage.error("加载收费详情失败");
  }
};

// 处理收费
const processPayment = (payment) => {
  currentPayment.value = payment;
  // 重置收费表单
  Object.assign(paymentProcessForm, {
    discountAmount: payment.discountAmount || 0,
    insurancePayment: payment.insurancePayment || 0,
    paymentMethod: payment.paymentMethod || "cash",
    windowNumber: payment.windowNumber || "01",
    notes: payment.notes || "",
  });
  paymentProcessDialog.visible = true;
};

// 确认收费
const confirmPayment = async () => {
  if (!currentPayment.value) return;

  try {
    // 验证支付信息
    if (paymentProcessForm.discountAmount < 0) {
      ElMessage.error("优惠金额不能为负数");
      return;
    }

    if (paymentProcessForm.insurancePayment < 0) {
      ElMessage.error("医保支付金额不能为负数");
      return;
    }

    if (personalPaymentAmount.value < 0) {
      ElMessage.error("个人支付金额不能为负数");
      return;
    }

    // 确认收费
    await ElMessageBox.confirm(
      `确认收取 ${currentPayment.value.patientName} 的费用 ¥${formatAmount(
        personalPaymentAmount.value
      )} 吗？`,
      "确认收费",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 更新收费信息
    currentPayment.value.paymentStatus = "completed";
    currentPayment.value.discountAmount = paymentProcessForm.discountAmount;
    currentPayment.value.insurancePayment = paymentProcessForm.insurancePayment;
    currentPayment.value.personalPayment = personalPaymentAmount.value;
    currentPayment.value.actualAmount = personalPaymentAmount.value;
    currentPayment.value.paymentMethod = paymentProcessForm.paymentMethod;
    currentPayment.value.paymentTime = new Date().toLocaleString();
    currentPayment.value.operatorName = username.value;
    currentPayment.value.windowNumber = paymentProcessForm.windowNumber;
    currentPayment.value.notes = paymentProcessForm.notes;

    ElMessage.success("收费成功");
    paymentProcessDialog.visible = false;
    loadPayments();
  } catch (error) {
    // 用户取消操作
    console.log("收费操作取消");
  }
};

// 显示退款对话框
const showRefundDialog = (payment) => {
  currentPayment.value = payment;
  Object.assign(refundForm, {
    paymentNo: payment.paymentNo,
    refundNo: `RF${Date.now()}`,
    patientName: payment.patientName,
    originalAmount: payment.actualAmount,
    refundAmount: payment.actualAmount,
    refundMethod: "original",
    refundReason: "",
  });
  refundDialog.visible = true;
};

// 确认退款
const confirmRefund = async () => {
  try {
    // 验证退款信息
    if (refundForm.refundAmount <= 0) {
      ElMessage.error("退款金额必须大于0");
      return;
    }

    if (!refundForm.refundReason.trim()) {
      ElMessage.error("请输入退款原因");
      return;
    }

    await ElMessageBox.confirm(
      `确认对 ${refundForm.patientName} 退款 ¥${formatAmount(
        refundForm.refundAmount
      )} 吗？`,
      "确认退款",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 更新原收费单状态
    const payment = payments.value.find(
      (p) => p.paymentNo === refundForm.paymentNo
    );
    if (payment) {
      payment.paymentStatus =
        refundForm.refundAmount < payment.actualAmount
          ? "partial_refund"
          : "refunded";

      // 记录退款信息
      payment.refundInfo = {
        refundNo: refundForm.refundNo,
        refundAmount: refundForm.refundAmount,
        refundMethod: refundForm.refundMethod,
        refundReason: refundForm.refundReason,
        refundTime: new Date().toLocaleString(),
        operatorName: username.value,
      };
    }

    ElMessage.success("退款处理成功");
    refundDialog.visible = false;
    loadPayments();
  } catch (error) {
    // 用户取消操作
    console.log("退款操作取消");
  }
};

// 导出数据
const exportData = () => {
  ElMessage.success("导出数据功能开发中");
};

// 导出对账单
const exportStatement = () => {
  ElMessage.success("导出对账单功能开发中");
};

// 刷新数据
const refreshData = () => {
  loadPayments();
  ElMessage.success("数据已刷新");
};

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return "0.00";
  return parseFloat(amount).toFixed(2);
};

// 格式化收费类型
const formatPaymentType = (type) => {
  const typeMap = {
    registration: "挂号收费",
    examination: "检查收费",
    medicine: "药品收费",
    treatment: "治疗收费",
    inpatient_deposit: "住院预交金",
  };
  return typeMap[type] || type;
};

// 格式化收费状态
const formatPaymentStatus = (status) => {
  const statusMap = {
    pending: "待收费",
    completed: "已收费",
    refunded: "已退款",
    partial_refund: "部分退款",
  };
  return statusMap[status] || status;
};

// 格式化支付方式
const formatPaymentMethod = (method) => {
  const methodMap = {
    cash: "现金",
    card: "银行卡",
    wechat: "微信支付",
    alipay: "支付宝",
    insurance: "医保结算",
  };
  return methodMap[method] || method;
};

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    pending: "warning",
    completed: "success",
    refunded: "info",
    partial_refund: "danger",
  };
  return typeMap[status] || "info";
};

// 初始化数据
onMounted(() => {
  loadPayments();
});
</script>

<style lang="scss" scoped>
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0; // 添加这行
  min-height: 100%; // 添加这行
  overflow-y: auto; // 确保有这行
}

/* 统计卡片样式 */
.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-icon.income {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stat-icon.pending {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #409eff, #79bbff);
}

.stat-icon.refund {
  background: linear-gradient(135deg, #f56c6c, #f89898);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 筛选卡片样式 */
.filter-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  flex: 1;
  min-width: 200px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表格样式 */
.payment-table {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.patient-avatar {
  flex-shrink: 0;
}

.amount {
  font-weight: bold;
  color: #67c23a;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 收费处理样式 */
.payment-process {
  padding: 10px 0;
}

.fee-details,
.fee-summary,
.payment-info {
  margin-bottom: 20px;
}

.fee-details h4,
.fee-summary h4,
.payment-info h4 {
  margin-bottom: 12px;
  color: #303133;
  font-weight: 500;
}

/* 详情抽屉样式 */
.payment-detail {
  padding: 0 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin-bottom: 12px;
  color: #303133;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-item {
    min-width: 180px;
  }
}

@media (max-width: 768px) {
  .content-area {
    padding: 10px;
  }

  .filter-row {
    flex-direction: column;
  }

  .filter-item {
    min-width: 100%;
  }

  .action-buttons {
    flex-direction: column;
  }

  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>